<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>axios发送get-post请求</title>
</head>

<body>
    <button id="btn1">发送get请求</button>
    <button id="btn2">发送post请求</button>
    <button id="btn3">发送get2请求</button>
    <div id="box1"></div>
    <ul id="box2"></ul>
    <div id="box3"></div>
    <script src="./js/axios.js"></script>
    <script>
        let btn1Ele = document.getElementById("btn1");
        let btn2Ele = document.getElementById("btn2");
        let box1Ele = document.getElementById("box1");
        let box2Ele = document.getElementById("box2");
        let btn3Ele = document.getElementById("btn3");
        let box3Ele = document.getElementById("box3")
        // 发送get请求
        // axios请求结果返回的是promise(承诺)，承诺成功或者失败
        // 获取其成功结果可在前面加个await等待其成功的结果
        // await不能单独使用，要在其所属的函数前面加个async
        btn1Ele.addEventListener("click", async () => {
            let { data } = await axios({
                method: "get",
                url: "http://localhost:5000/user",
            });
            let { name, age } = data;
            box1Ele.innerText = `名字:${name},年龄:${age}`;
        });

        btn2Ele.addEventListener("click", async () => {
            let { data } = await axios({
                method: "post",
                url: "http://localhost:5000/fruit",
            });
            let lis = "";
            data.forEach((item) => {
                lis += `<li>${item}</li>`;
                box2Ele.innerHTML = lis;
            });
        });

        btn3Ele.addEventListener("click", async () => {
            let { data } = await axios({
                method: "get",
                url: "http://localhost:5000/songs",
            });
            let div = "";
            data.forEach((id,name,author) => {
                div += `id:${id},名字:${name},作者:${author}`;
                box2Ele.innerHTML = div;
            });
        });
    </script>
</body>

</html>